import store from '@/store'

import Vue from 'vue'
import VueRouter from 'vue-router'

// 重写push方法
// 先把VueRouter原型对象的push保存一份
const originalPush = VueRouter.prototype.push
// 第一个参数 往哪里跳转（传递哪些函数） 第二个参数 成功的回调 第三个参数 失败的回调
// originalPush里的this会指向window 我们需要call来改变this指向
// call可以调用一次，篡改this的指向一次
VueRouter.prototype.push = function (location, resolve, reject) {
  if (resolve && reject) {
    originalPush.call(this, location, resolve, reject)
  } else {
    originalPush.call(
      this,
      location,
      () => {},
      () => {}
    )
  }
}

Vue.use(VueRouter)

// 导入所需组件
const AppTabbar = () => import('@/components/app-tabbar.vue')
const Home = () => import('@/views/home/index.vue') // 首页  如果后面是index.vue文件就可以省略不写
const Question = () => import('@/views/question') // 问答
const Video = () => import('@/views/video') // 视频
const User = () => import('@/views/user')
const Article = () => import('@/views/article') // 文章详情
const Login = () => import('@/views/login')
const UserProfile = () => import('@/views/user/profile')
const UserChat = () => import('@/views/user/chat') // 小智障
const routes = [
  // 首页
  {
    path: '/',
    components: {
      default: Home,
      tabbar: AppTabbar
    }
  },
  // 问答
  {
    path: '/question',
    components: {
      default: Question,
      tabbar: AppTabbar
    }
  },
  // 视频
  {
    path: '/video',
    components: {
      default: Video,
      tabbar: AppTabbar
    }
  },
  // 我的
  {
    path: '/user',
    components: {
      default: User,
      tabbar: AppTabbar
    }
  },
  // 文章详情
  {
    path: '/article',
    component: Article
  },
  // 登录
  { path: '/login', component: Login },
  { path: '/user/profile', component: UserProfile },
  { path: '/user/chat', component: UserChat }
]

const router = new VueRouter({
  routes
})

// 导航守卫
router.beforeEach((to, from, next) => {
  const token = store.state.user.token
  if (!token && to.path.startsWith('/user')) {
    return next(
      '/login?returnUrl=' + encodeURIComponent(router.currentRoute.fullPath)
    )
  }
  // 其他情况放行
  next()
})

export default router
